const jwt = require('jsonwebtoken')

 
/**
 * 
 * @param {*} num 
 * @param {*} type hour/minute/second
 */
function timeTosecond(num, type) {
  let fun = {
    hour(num) {
      return num*60*60
    },
    minute(num) {
      return num*60
    },
    second(num) {
      return num
    }
  }[type]
  return fun(num)
}

/**
 * 签证
 * @param {*} username 用户名
 * @param {*} privateKey 私钥
 * @returns token
 */
function sign(username, privateKey, time) {
  let content = {username}
  let token = jwt.sign(content, privateKey, {
    expiresIn: timeTosecond(time.num, time.type)
  })
 
  return token
}

/**
 * 验证token 
 * @param {*} token 
 * @returns Promse 成功返回json对象包含开始结束时间
 */
function verify(token, privateKey) {
  return new Promise((resolve, reject) => {
    jwt.verify(token, privateKey, (err, decode) => {
      if (err) {
        reject({
          type: err.name
        })
      } else {
        resolve(decode)
      }
    })
  })
}

module.exports = {
  sign,
  verify
}
